/**
 * 
 * @authors youzhao.zhou@pandauu.com
 * @date    2016-09-08 15:12:44
 * @version $Id$
 * 
 * 车票兑换页
 * 
 */

;(function(root,factory){

  var dependent = {
    zepto : typeof exports !== 'undefined' ? require('./zepto.js')&&root.$ : root.$,
    underscore : typeof exports !== 'undefined' ? require('../../public_src/js/underscore/underscore.js') : root._,
    Project : typeof exports !== 'undefined' ? require('../../public_src/js/1_self/1_project.js') : root.Project,
    conf : typeof exports !== 'undefined' ? require('../../public_src/js/1_self/2_config.js') : root.conf,
    log : typeof exports !== 'undefined' ? require('../../public_src/js/1_self/3_log.js') : root.p_log,
    path: {
      zepto : '../../p_src/js/convert/zepto.js',
      underscore : '../../public_src/js/underscore/underscore.min',
      Project : '../../public_src/js/1_self/1_project',
      conf : '../../public_src/js/1_self/2_config',
      log : '../../public_src/js/1_self/3_log',
    }
  };
  
  if(typeof exports === 'object' && typeof module === 'object'){

    module.exports = factory(exports,
      dependent.zepto, 
      dependent.underscore,
      dependent.Project, 
      dependent.conf,
      dependent.log
    );

  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.

    define(['exports', 
      dependent.path.zepto, 
      dependent.path.underscore,
      dependent.path.Project, 
      dependent.path.conf,
      dependent.path.log
      ], factory);
  } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
    // CommonJS
    factory(exports, 
      dependent.zepto, 
      dependent.underscore,
      dependent.Project, 
      dependent.conf,
      dependent.log
    );
  } else {
    // Browser globals
    if (!(dependent.Project||dependent.conf||dependent.log)) {
      throw('请加载相应的文件！');
    }
    factory({},
      dependent.zepto, 
      dependent.underscore,
      dependent.Project, 
      dependent.conf,
      dependent.log
    );
  }

})((typeof window !== 'undefined' ? window : this) ,function(exports,$ ,_ , Project, conf, log, undefined){
  'use strict';

  setTimeout(function(){

    if (typeof $ === 'undefined') {
      $ = window.$;
    }

    if (typeof _ === 'undefined') {
      _ = window._;
    }

    /*
      调试开关
    */
    log._logToggle(false);

    var urlConf = conf._conf;
    /*
      项目工具类对象
    */
    var project = new Project();

    var params = project.getQueryStringObj();
    /*
      设置导航头部
    */
    project.setHTML('.middle', '咨询列表');

    
    /*
      刷新页面或者打开页面获取数据
    */

    $.ajax({
      url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.threadList,
      type: 'GET',
      dataType: 'json'
    })
    .done(function(data) {
      log._log(data);
      var test = [
        {
          //不变的数据
          /*
            头像
            昵称
          */
          //可变的数据
          /*
            消息
            时间
            是否有订单
            新消息数
            总消息数
            发送者
          */
          invariantData: {
            id: '1',
            avatar: 'http://test.pandauu.com/ic_avatar_default_02.png',
            nickname: '的所得税',
            url: 'http://test.pandauu.com/single/kf/html/service.php?thread_id=1',
          },
          variableData: {
            msg: 'asfsdfsdfs',
            time: '2016-09-27 12:30:26',
            hasOrder: 1,
            noRead: 1,
            noReadNum: 3,
            totle: 101,
            sender: '用户',
          }
        },
        {
          invariantData: {
            id: '2',
            avatar: 'http://test.pandauu.com/ic_avatar_default_02.png',
            nickname: '的所得税1',
            url: 'http://test.pandauu.com/single/kf/html/service.php?thread_id=2',
          },
          variableData: {
            msg: '[图片]',
            time: '2016-09-27 12:30:26',
            hasOrder: 0,
            noRead: 0, //
            noReadNum: 0,
            totle: 99,
            sender: '熊猫晓晓',
          }
        },
        {
          invariantData: {
            id: '3',
            avatar: 'http://test.pandauu.com/ic_avatar_default_02.png',
            nickname: '的所得税2',
            url: 'http://test.pandauu.com/single/kf/html/service.php?thread_id=3',
          },
          variableData: {
            msg: '放的地方和个梵蒂冈和梵蒂冈和梵蒂冈和梵蒂冈和梵蒂冈和对方打广告回复',
            time: '2016-09-27 12:30:26',
            hasOrder: 0,
            noRead: 1,
            noReadNum: 12,
            totle: 12,
            sender: '熊猫晓晓',
          }
        }
      ];


      var threadDatas = [];
      var temp = null;
      var httpData = null;
      var dataTpl = null;

      if (data.code === 0) {
        httpData = data.data;
        for(var i=0, len=httpData.length ; i<len ; i++){
          if (!threadDatas[i]) {
            threadDatas[i] = new Thread();
          }
          if (!dataTpl) {
            dataTpl = {};
          }
          $('#invariantData input').each(function(index, el) {
            
          });
          threadDatas[i].setInvariantData(
            httpData[i][$('#invariantData [data-front="id"]').attr('name')],
            httpData[i][$('#invariantData [data-front="nickname"]').attr('name')],
            httpData[i][$('#invariantData [data-front="avatar"]').attr('name')]
          );
          threadDatas[i].setUrl(
            urlConf.root + urlConf.static + 'service.php?thread_id=',
            httpData[i][$('#invariantData [data-front="id"]').attr('name')]
          );

          $('#variableData input').each(function(index, el) {
            if (!dataTpl['data1']) {
              dataTpl['data1'] = {};
            }
            if (!dataTpl['data2']) {
              dataTpl['data2'] = {};
            }

            if (el.getAttribute('data-name')) {
              dataTpl['data2'][el.name] = el.getAttribute('data-front');

            }
            dataTpl['data1'][el.name] = el.getAttribute('data-front');        
          });
          log._log(dataTpl);
          threadDatas[i].setVariableData(httpData[i], dataTpl['data1']);
          threadDatas[i].setMsgInfo(httpData[i].last_msg, dataTpl['data2']);
          threadDatas[i].hasNoRead();
          threadDatas[i].setMsgType();


        }
        $('#threads').html(_.template($('#threadsTpl').html())({list: threadDatas}));

        log._log(threadDatas);
      }else if(data.code === 100){
        window.location.href = urlConf.root + urlConf.static + 'login.php';
      }

    })
    .fail(function() {
      log._log("error");
    })
    .always(function() {
      log._log("complete");
    });
    


    function Thread(){
      this.invariantData = {};
      this.variableData = {};
    }

    Thread.prototype.setInvariantData = function(id, nickname, avatar){
      var invariantData = this.invariantData;
      invariantData.id = id||'';
      invariantData.nickname = nickname||'';
      invariantData.avatar = avatar||'';
    };

    Thread.prototype.setUrl = function(url,id){
      var invariantData = this.invariantData;
      invariantData.url = (url||'') + (id||'');
    };
    
    Thread.prototype.setVariableData = function(obj,dataTpl){
      var variableData = this.variableData;
      log._log(obj['noread']);
      for(var k in dataTpl){
        if (typeof obj[k] !== 'object') {
          variableData[dataTpl[k]] = typeof obj[k] === 'number'? obj[k]:(obj[k]||'');
        }
        
      }
    };

    Thread.prototype.hasNoRead = function(){
      var variableData = this.variableData;

      variableData.noRead = variableData.noReadNum? 1:0;

    };
    Thread.prototype.setMsgInfo = function(obj,dataTpl){
      var variableData = this.variableData;
      log._log(obj['noread']);
      for(var k in dataTpl){
        if (typeof obj[k] !== 'object') {
          variableData[dataTpl[k]] = typeof obj[k] === 'number'? obj[k]:(obj[k]||'');
        }
        
      }

    };
    Thread.prototype.setMsgType = function(){
      var variableData = this.variableData;
      var invariantData = this.invariantData;
      
      variableData.sender = variableData.isKf? variableData.sender:'用户';
      variableData.msg = variableData.type == 2? '[图片]':variableData.msg;

    };

    online();
    function online(){
      $.ajax({
        url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.online,
        type: 'GET',
        dataType: 'json'
      })
      .done(function() {
        setTimeout(function(){
          online();
        },2000);
        log._log("success");
      })
      .fail(function() {
        log._log("error");
      })
      .always(function() {
        log._log("complete");
      });
    }
    window.addEventListener('unload',function(){
      log = null;
      $.ajax({
        url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.offline,
        type: 'GET',
        dataType: 'json'
      })
      .done(function() {
        log._log("success");
      })
      .fail(function() {
        log._log("error");
      })
      .always(function() {
        log._log("complete");
      });
    },false);

  },0);

});
